<?php
/**
 * Create By: PhpStorm
 * User: yihua
 * File: UserAddress.php
 * Date: 2017/1/5
 * Time: 23:22
 */

namespace app\api\model\page\user;

use app\library\PageBase;
use app\api\model\dao\UserAddress;
use app\library\Flag;
use app\library\Error;
use think\Validate;

class AddUserAddress extends PageBase
{
    //private $tableUserAddress;
    private $objUserAddressModel;

    public function __construct()
    {
        parent::__construct();
        $this->objUserAddressModel = new UserAddress();
    }

    public function excute($param)
    {
        if (!$this->check($param)) {
            return $this->getRes(Error::ERR_PARAM);
        }
        $arrUserAddress = $this->objUserAddressModel->getAddressByUserid($param['user_id']);
        //每个用户只能保存5个地址?·
        $addressCount = count($arrUserAddress);
        if ($addressCount >= Flag::ADDRESS_MAX) {
            return $this->getRes(Error::ERR_USER_ADDRESS_MAX);
        }

        $result = $this->objUserAddressModel->addAddress($param);
        if ($result === false) {
            return $this->getRes(Error::ERR_SYS);
        } else {
            return $this->getRes();
        }
    }

    public function check($param)
    {
        $rule = [
            'address_name' => 'require|max:25',
            'user_id' => 'require',
            'consignee' => 'require',
            'address' => 'require',
            'mobile' => 'require',
            'province' => 'require',
            'city' => 'require',
            'district' => 'require',
        ];
        $msg = [
            'address_name.require' => '名称必须',
            'address_name.max' => '名称最多不能超过25个字符',
            'user_id.require' => 'userid必须',
            'consignee.require' => 'consignee必须',
            'address.require' => 'address必须',
            'mobile.require' => 'mobile必须',
            'province.require' => 'province必须',
            'city.require' => 'city必须',
            'district.require' => 'district必须',
        ];
        $validate = new Validate($rule, $msg);
        $result = $validate->check($param);
        if (!$result) {
            return $validate->getError();
        }
        return $result;
    }

}